import gtk
import os
import utils
from threading import Thread

class UpdateSVN(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self)
        
        VBox=gtk.VBox(spacing=5)
        self.progressbar=gtk.ProgressBar()
        self.label=gtk.Label()
        VBox.pack_start(self.progressbar)
        VBox.pack_end(self.label, False)
        
        self.add(VBox)
        
        self.set_title("Updating hydroxygen...")
        
        self.connect("delete-event", self.try_close)
        self.connect("destroy-event", self.try_close)
        icon=utils.getPixbufFromName("./images/logo.png", 48)
        self.set_icon_list(icon)
        self.set_border_width(5)
        self.set_size_request(300, 60)
        self.set_resizable(False)
        self.set_position(gtk.WIN_POS_CENTER_ALWAYS)
        self.show_all()
        gtk.gdk.threads_init()
        self.progressMove=ProgressMove(self.moveBar)
        self.progressMove.start()
        updating=UpdateThread(self.finish, self.updateLabel, self.progressMove.set_state)
        updating.start()
        gtk.main()
    
    def try_close(self, obj=None, event=None):
        #this doesn't work... damn.
        print "impedisco la chiusura della finestra"
        self.show_all()
    
    def finish(self):
        self.progressMove.stop()
        self.hide()
        gtk.main_quit()
    
    def moveBar(self):
        gtk.gdk.threads_enter()
        self.progressbar.pulse()
        gtk.gdk.threads_leave()
    
    def updateLabel(self, text):
        gtk.gdk.threads_enter()
        self.label.set_text(text)
        gtk.gdk.threads_leave()


class UpdateThread(Thread):
    def __init__(self, finish, updateLabel, set_state):
        Thread.__init__(self)
        self.set_text=updateLabel
        self.finish=finish
        self.state=set_state
        
    def run(self):
        self.state(1)
        self.set_text("Downloading hydroxygen from internet...")
        if os.path.exists(os.path.expanduser("~")+"/.icons/hydroxygen/") and os.path.exists(os.path.expanduser("~")+"/.icons/hydroxygen/.svn"):
            os.system("cd ~/.icons/hydroxygen && svn update")
        else:
            os.system("cd ~/.icons/ && svn checkout http://hydroxygengnomeicontheme.googlecode.com/svn/trunk/ hydroxygen")
        self.state(2)
        self.set_text("Update complete!")
        self.finish()
        
class ProgressMove(Thread):
    def __init__(self, movebar):
        Thread.__init__(self)
        self.stopNow=False
        self.movebar=movebar
        self.update_state=0
    
    def stop(self):
        self.stopNow=True
    
    def set_state(self, state):
        self.update_state=state
    
    def run(self):
        import time
        while (1) and self.stopNow==False:
            time.sleep(0.1)
            self.movebar()
